	package org.edu.isis.bravefox;
	
	import java.io.BufferedReader;
	import java.io.ByteArrayInputStream;
	import java.io.IOException;
	import java.io.InputStreamReader;
	import java.net.DatagramPacket;
	import java.net.DatagramSocket;
	import java.net.InetAddress;
	import java.net.SocketException;
	import java.net.UnknownHostException;

import org.edu.isis.bravefox.SocketCamera.SocketCameraThread;
	
	import android.app.Activity;
	import android.app.AlertDialog;
	import android.app.Dialog;
	import android.app.ProgressDialog;
import android.content.Context;
	import android.content.DialogInterface;
	import android.os.AsyncTask;
	import android.os.Bundle;
	import android.util.Log;
import android.view.Display;
	import android.view.LayoutInflater;
	import android.view.MotionEvent;
import android.view.SurfaceHolder;
	import android.view.View;
	import android.view.ViewGroup;
import android.view.WindowManager;
	import android.view.View.OnTouchListener;
	import android.widget.Button;
	import android.widget.EditText;
	import android.widget.Toast;
	
import static java.lang.Math.*;
	
	public class CtrlTest extends Activity {
		
		SurfaceHolder mSurfaceHolder;
		Context mContext;
		SocketCamera mSocketCamera;
		SocketCameraThread scThread;
		Button	 bMove1;
		ProgressDialog spinner;
		Display display;
		
		DatagramSocket socket;
		InetAddress robotAddress;
		int robotPort = 25000; 
		int packetSize = 128;
		int dpadSize = 100; // Pixels
		
		int curX = 0;
		int curY = 0;
		String direction = "Stop";
		
		Activity activity = this;
		
		ConnectToRobot control;
		
		boolean sendMessages = true;
		
		String robotAddressString = "10.0.2.2";
		String passwordString = "password";
		
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	    	
	    	
	    	
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.ctrltest);
	        
	        //spinner = ProgressDialog.show(getBaseContext(), "Connecting", "Please Wait...");
	   
	        mSocketCamera = (SocketCamera) findViewById(R.id.scamera);
	        bMove1 = (Button) findViewById(R.id.bMove1);
	        display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
	        dpadSize = display.getHeight() * 20 / 100;
	        //bMove1.setHeight(dpadSize);
	        //bMove1.setWidth(dpadSize);
	        //bMove1.invalidate();
	        
	        bMove1.setOnTouchListener(new OnTouchListener() 
	        {
	
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					
					float XPOS = (event.getX() - dpadSize) / dpadSize;
					float YPOS = (dpadSize - event.getY()) / dpadSize;
					float aX = abs(XPOS);
					float aY = abs(YPOS);
					float YT2 = aY * 2;
					float YD2 = aY / 2;
					
					
					if ((aX > 0.15 || aY > 0.15) && aX < 1 && aY < 1)
					{
						if (event.getAction() == MotionEvent.ACTION_UP)
						{ setStatus(0,0,"Stop"); } else {
							if (YD2 < aX && aX < YT2)
							{
								if (YPOS > 0)
								{
									if (XPOS > 0) {
										setStatus(-534,-178, "Forward Right");
									} else {
										setStatus(-178,-534, "Forward Left");
									}
								} else
								{
									if (XPOS > 0)
									{
										setStatus(178,534, "Reverse Right");
									} else
									{
										setStatus(534,178, "Reverse Left");
									}
								}
							} else
							{
								// Is full direction
								if (XPOS > YPOS)
								{
									if (XPOS > -YPOS)
									{
										setStatus(-200,200, "Right");
									} else
									{
										setStatus(400,400, "Reverse");
									}
								} else
								{
									if (XPOS > -YPOS)
									{
										setStatus(-400,-400, "Forward");
									} else
									{
										setStatus(200, -200, "Left");
									}
								}
							}
						}
					} else
					{
						setStatus(0,0,"Stop");
					}
					
					return false;
				}
	        });
	     
	    }
	    
	    private void setStatus (int x, int y, String status)
	    {
	    	direction = status;
	    	curX = x;
	    	curY = y;
	    }
	    
	    @Override
	    public void onStart()
	    {
	    	super.onStart();
	    	
	    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    	LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
			View layout = inflater.inflate(R.layout.connectdialog,(ViewGroup) findViewById(R.id.layout_root));
			builder.setView(layout);
	    	
			final EditText ipArea = (EditText) layout.findViewById(R.id.ip_area);
			final EditText passwordArea = (EditText) layout.findViewById(R.id.password_area);
			
			builder.setPositiveButton("Connect", new DialogInterface.OnClickListener() 
			{  
	
				@Override
				public void onClick(DialogInterface d, int arg1) {
					
					if(ipArea != null)
					{
						robotAddressString = ipArea.getText().toString();
						passwordString = passwordArea.getText().toString(); 
						scThread = mSocketCamera.getThread();
						scThread.connect(robotAddressString, display.getWidth(), display.getHeight(), 9889);
						
						control = (ConnectToRobot) new ConnectToRobot().execute();
					}
					
				}	
				
			});
			
			builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
			{           
				public void onClick(DialogInterface d, int id) 
				{
					// end the activity
					activity.finish();
				}
			});
			
			builder.create();
			builder.setCancelable(false);
			builder.show();
			
		}
			
	    
	    @Override    protected void onStop() {       
	    	
	    	super.onStop();
	    	
	    	if(control != null)
	    	{
	    		control.cancel(true);
	    		sendMessage("disconnect");
	    	}
	    	
	    	sendMessages = false;
	    	
	    	Log.d("CtrlTest", "Stopped");
	    	
	    }
	    
		protected void sendMessage(String message) {
			
			byte[] messageBytes = message.getBytes();
			DatagramPacket startGram =  new DatagramPacket(messageBytes, messageBytes.length, robotAddress, robotPort);
			try {
				socket.send(startGram);
			} catch (IOException e) {
				Log.d("Send Fail", "Failed to Send");
				e.printStackTrace();
			}
			
		}
		
	    private class ConnectToRobot extends AsyncTask<Void, Void, Void>
	    {
	    	
	    	@Override
	    	protected Void doInBackground(Void... params)
	    	{
		        try {
					
		        	socket = new DatagramSocket();
		        	robotAddress = InetAddress.getByName(robotAddressString);
					
					String message = "control " + passwordString;
					
					byte[] messageBytes = message.getBytes();
					DatagramPacket startGram =  new DatagramPacket(messageBytes, messageBytes.length, robotAddress, robotPort);
					socket.send(startGram);
					
					// wait for response
					
					byte[] receiveBytes = new byte[packetSize];
					DatagramPacket receivedPacket = new DatagramPacket(receiveBytes, packetSize);
					
					socket.receive(receivedPacket);
			
					InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(receiveBytes));
					BufferedReader inFromRobot = new BufferedReader(reader, packetSize);
			    	 
					Log.d("CtrlTest", "Message Received");
					
					String line= inFromRobot.readLine();
					
					Log.d("CtrlTest", line);
					
					if(line.contains("control ok"))
					{
						//spinner.dismiss();
						
						//Toast.makeText(getBaseContext(), "Connected", 5000).show();
						
						while(sendMessages)
						{
							// send updates to robot
							
							try {
							
								
								String coords = curX + " " + curY;
	
								Log.d("Sending Message: ", coords);
								
								byte[] coordsBytes = coords.getBytes();
								DatagramPacket coordsGram =  new DatagramPacket(coordsBytes, coordsBytes.length, robotAddress, robotPort);
								socket.send(coordsGram);
								Thread.sleep(1000);
								
							} catch (IOException e) {
								e.printStackTrace();
							}
							catch (InterruptedException e) {
								e.printStackTrace();
							}
							
						}
					}
					else
					{
						//spinner.dismiss();
						//Toast.makeText(getBaseContext(), "Failed to connect. Try Again", 5000);
						finish();
					}
					
					
					
				} catch (SocketException e) {
					Log.d("Socket Fail", "Connection has failed");
					//spinner.dismiss();
					Toast.makeText(getBaseContext(), "Failed to connect. Try Again", 5000);
					finish();
					e.printStackTrace();
				} catch (UnknownHostException e) {
					Log.d("Socket Fail", "Connection has failed");
					//spinner.dismiss();
					Toast.makeText(getBaseContext(), "Failed to connect. Try Again", 5000);
					finish();
					e.printStackTrace();
				} catch (IOException e) {
					Log.d("Socket Fail", "Connection has failed");
					//spinner.dismiss();
					Toast.makeText(getBaseContext(), "Failed to connect. Try Again", 5000);
					finish();
					e.printStackTrace();
				}
				return null;
		    
		    }
	    }
		
	}